﻿using System;
using WindowsGame.Components;
using WindowsGame.GameObjects;
using WindowsGame.Manager;
using WindowsGame.Library.ProxyObjects;

namespace WindowsGame.Builder
{
	public class GameObjectBuilder
	{
		private ProxyObjectBuilder proxyObjectBuilder;

		public GameObjectBuilder(ProxyObjectBuilder proxyObjectBuilder)
		{
			this.proxyObjectBuilder = proxyObjectBuilder;
		}

		public T BuildGameObject<T>(String assetName) where T : GameObject
		{
			ProxyObject proxyObject = proxyObjectBuilder.GetProxyObject(assetName);
			return (T)BuildGameObject(proxyObject);
		}

		public GameObject BuildGameObject(String assetName)
		{
			return BuildGameObject<GameObject>(assetName);
		}

		public GameObject BuildGameObject(ProxyObject proxyObject)
		{
			if (null == proxyObject)
			{
				return null;
			}

			String cast = proxyObject.Cast;
			String typeName = String.Format("{0}.{1}", "WindowsGame.GameObjects", cast);
			Type type = Type.GetType(typeName);

			GameObject gameObject = (GameObject)Activator.CreateInstance(type);

			Char[] delim = new[] { '_' };
			foreach (ProxyComponent proxyComponent in proxyObject.Components)
			{
				String[] split = proxyComponent.Name.Split(delim);
				String name = split[0];

				typeName = String.Format("{0}.{1}", "WindowsGame.Components", name);
				type = Type.GetType(typeName);

				BaseGameComponent gameComponent = (BaseGameComponent)Activator.CreateInstance(type);

				gameComponent.Initialize(gameObject, proxyComponent);
				gameObject.AddComponent(name, gameComponent);
			}

			return gameObject;
		}

		public ProxyObjectBuilder ProxyObjectBuilder { get { return proxyObjectBuilder; } }
	}
}